package com.kay.controller;

import com.kay.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Author: Kay
 * @CreateDate: 2021/9/17$ 21:51$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/9/17$ 21:51$
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册接⼝
     *
     * @param email
     * @param password
     * @param code
     * @return true成功，false失败
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable("email") String email, @PathVariable("password") String password,
                            @PathVariable("code") String code) {

        return userService.register(email, password, code);
    }

    /**
     * 是否已注册, 根据邮箱判断,true代表已经注册过，false代表尚未注册
     *
     * @param email
     * @return
     */
    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和
     * 密码⽣成token，token存⼊数据库，并写⼊cookie
     * 中，登录成功返回邮箱地址，重定向到欢迎⻚
     *
     * @param email
     * @param password
     * @return
     */
    @GetMapping("/login/{email}/{password}")
    public String login(@PathVariable("email") String email, @PathVariable("password") String password) {
        return  userService.login(email, password);
    }

    private void setCookie(String key, String value, HttpServletResponse response) {
        Cookie cookie = new Cookie(key, value);
        cookie.setDomain("sso.kay");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     *
     * @param token
     * @return
     */
    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token) {
        return userService.info(token);
    }
}
